﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace TestRabbitMQ
{
    public static class StartupExtensions
    {
        internal static IServiceCollection ServiceCollection;

        public static void AddRabbitMQ(this IServiceCollection services, Action<RabbitMQConfig> setupAction)
        {
            if (setupAction == null)
            {
                throw new ArgumentNullException(nameof(setupAction));
            }

            ServiceCollection = services;

            // 注入
            services.AddSingleton<IRabbitMQConsumerApplication, RabbitMQConsumerApplication>();
            services.AddSingleton<IPublishClient, PublishClient>();

            //注入RabbitMQ全局配置
            services.Configure(setupAction);

            // 构建容器
            IServiceProvider serviceProvider = services.BuildServiceProvider();

            // 启动MQ消费
            Task.Run(() =>
            {
                serviceProvider.GetService<IRabbitMQConsumerApplication>().Start();
            });

        }
    }
}
